﻿using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class SpriteContentSizeFitter : MonoBehaviour
{
    public TextMeshPro text;
    public float outWidth = 0.1f;
    public Transform offsetObjTransform;
    // 按钮
    public Transform btnObjTransform;
    public float btnSpace = 0; // 按钮和文本间隔
    public float btnObjSize = 0;// 按钮尺寸
    private SpriteRenderer render;

    public bool isTest;
    void Start()
    {
        if (text)
        {
            text.RegisterDirtyLayoutCallback(UpdateContent);
        }
        render = gameObject.GetComponent<SpriteRenderer>();
    }

    public void UpdateContent()
    {
        // 获得text的尺寸
        if (text)
        {
            RectTransform tf = text.transform as RectTransform;
            if (render)
            {
                Vector2 size = render.size;
                var baseSizeX = tf.sizeDelta.x * 0.5f * 0.1f + 2 * outWidth;
                if (offsetObjTransform)
                {
                    offsetObjTransform.localPosition = new Vector3(baseSizeX / 2 - 0.09f, 0, 0);
                    size.x = baseSizeX + 0.15f;
                    render.size = size;
                }
                else if (btnObjTransform)
                {
                    size.x = (tf.sizeDelta.x * 0.1f + 2 * outWidth) + btnObjSize + btnSpace;
                    float halfSize = (btnObjSize + btnSpace) * 0.5f;
                    Vector3 localPos = btnObjTransform.localPosition;
                    localPos.x = size.x / 2 - outWidth - btnObjSize * 0.5f;
                    btnObjTransform.localPosition = localPos;

                    Vector3 localPos1 = text.transform.localPosition;
                    localPos1.x = -halfSize;
                    text.transform.localPosition = localPos1;

                    render.size = size;
                }
                else
                {
                    size.x = baseSizeX;
                    render.size = size;
                }
            }
        }
    }
}
